using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Xml;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Drawing;

namespace BlogControl
{
    class PostsView
    {
        private HtmlTextWriter writer;
        private Blog _control;
        private string curFileName;
        public PostsView(HtmlTextWriter writer,Blog control)
        {
            this.writer=writer;
            this._control = control;
        }
        public void RenderPostsView()
        {
            writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            if (_control.AllowPaging && _control.PagerVisible && (_control.PagerLocation == PagerPosition.Top || _control.PagerLocation == PagerPosition.TopAndBottom) && string.IsNullOrEmpty(_control.DatesFilter))
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                RenderPager();
                writer.RenderEndTag();//td
                writer.RenderEndTag();//tr
            }

            string[] files = _control.Files;
            int i;
            if (_control.AllowPaging && string.IsNullOrEmpty(_control.DatesFilter))//if filter we don't paging or posts limit per page
            {
                i = (_control.PostsPerPage * _control.PageIndex);
            }
            else
            {
                i = 0;
            }
            int postsCounter = 0;

            for (; i < files.Length && (!string.IsNullOrEmpty(_control.DatesFilter) || postsCounter < _control.PostsPerPage); i++, postsCounter++)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                if (_control.IsDesignMode)
                {
                    WritePost(null, _control.ShowFullBlogsOnPreivewPage);
                }
                else
                {
                    WritePost(files[i], _control.ShowFullBlogsOnPreivewPage);
                }
                writer.RenderEndTag();//td
                writer.RenderEndTag();//tr
            }
            if (files.Length == 0)
            {
                if (!string.IsNullOrEmpty(_control.NoPostsText))
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                    if (!string.IsNullOrEmpty(_control.NoPostsCSS))
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.NoPostsCSS);
                    }
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(_control.NoPostsColor));
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write(_control.NextPageText);
                    writer.RenderEndTag();//td
                    writer.RenderEndTag();//tr
                }
            }
            if (_control.ShowAddPostButton)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                Button bt;
                if (_control.IsDesignMode)
                {
                    bt = new Button();
                    bt.Text = _control.AddPostButtonText;
                }
                else
                {
                    bt = (Button)_control.Controls[_control.addPostButtonIndex];
                }
                bt.RenderControl(writer);
                writer.RenderEndTag();//td
                writer.RenderEndTag();//tr
            }
            if (_control.AllowPaging && _control.PagerVisible && (_control.PagerLocation == PagerPosition.Bottom || _control.PagerLocation == PagerPosition.TopAndBottom) && string.IsNullOrEmpty(_control.DatesFilter))
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                RenderPager();
                writer.RenderEndTag();//td
                writer.RenderEndTag();//tr
            }
            writer.RenderEndTag();//table

        }

        private void RenderPager()
        {
            if (!string.IsNullOrEmpty(_control.PagerCSS))
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.PagerCSS);
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            int pagesCount = (int)Math.Ceiling((double)_control.FilesCount / (double)_control.PostsPerPage);

            if (_control.Mode == PagerMode.NumericPages)
            {
                for (int i = 0; i < pagesCount; i++)
                {
                    
                    if (i == _control.PageIndex)
                    {
                        writer.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(_control.PagerSelectedPageColor));
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.Write((i + 1).ToString());
                        writer.RenderEndTag();
                    }
                    else
                    {
                        LinkButton lb;
                        if (_control.IsDesignMode)
                        {
                            lb = new LinkButton();
                        }
                        else
                        {
                            lb = (LinkButton)_control.Controls[_control.pagingIndexes[i]];
                        }
                        lb.ForeColor = _control.PagerColor;
                        lb.Text = (i + 1).ToString();
                        lb.RenderControl(writer);
                    }
                    
                }
            }
            else
            {
                if (_control.PageIndex > 0)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    LinkButton lb;
                    if (_control.IsDesignMode)
                    {
                        lb = new LinkButton();
                    }
                    else
                    {
                        lb = (LinkButton)_control.Controls[_control.pagingIndexes[0]];
                    }
                    lb.Text = _control.PreviousPageText;
                    lb.RenderControl(writer);
                    writer.RenderEndTag();
                }
                if (pagesCount > (_control.PageIndex + 1))
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    LinkButton lb;
                    if (_control.IsDesignMode)
                    {
                        lb = new LinkButton();
                    }
                    else
                    {
                        lb = (LinkButton)_control.Controls[_control.pagingIndexes[_control.PageIndex + 1]];
                    }
                    lb.Text = _control.NextPageText;
                    lb.RenderControl(writer);
                    writer.RenderEndTag();
                }
            }

            writer.RenderEndTag();

        }
        private void WritePost(string filepath, bool fullBody)
        {
            XmlDocument doc = new XmlDocument();
            if (_control.IsDesignMode)
            {
                curFileName = "temp";
                doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><Post xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"Template.xsd\">  <Title publishDate=\"2002-10-10T12:00:00\">    My Post Title  </Title>  <Writer>    Post Writer  </Writer>  <Body>    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body    My Post Body My Post Body My Post Body  </Body>    <Comments>    <comment date=\"2002-10-10T12:00:00\" writer=\"comment 1 writer\">      <subject>       comment 1 subject      </subject>      <body>        comment 1 body      </body>    </comment>    <comment date=\"2002-10-10T12:00:00\" writer=\"comment 2 writer\">      <subject>comment 2 subject      </subject>      <body>        comment 2 body      </body>    </comment>  </Comments></Post>");
            }
            else
            {
                curFileName = Path.GetFileNameWithoutExtension(filepath);
                StreamReader sr = FilesManager.OpenFile(filepath);
                doc.Load(sr);
                sr.Close();
            }
            if (_control.BodyBorderStyle != BorderStyle.None &&
                _control.BodyBorderStyle != BorderStyle.NotSet)
            {
                HtmlManager.SetBorderStyle(writer, _control.BodyBorderStyle, _control.BodyBorderColor, _control.BodyBorderWidth);
            }
            writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
          
            RenderSubjectLine(doc);

         

            RenderBody(fullBody, doc);
            writer.RenderEndTag();
            writer.RenderEndTag();//tr
            if ((_control.AllowComments && _control.CurrentAction == Blog.ActionType.ViewPost) || (_control.AllowCommentsOnPreviewPage && (_control.CurrentAction == Blog.ActionType.Default || _control.CurrentAction== Blog.ActionType.AddComment)))
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                if (_control.AddCommentBoxCSS != null)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.AddCommentBoxCSS);
                }
                writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
                writer.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(_control.AddCommentsBoxTextColor));
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                CommentsManager.WriteAddCommentPanel(writer, curFileName, _control);
                writer.RenderEndTag();//td
                writer.RenderEndTag();//tr
            }

            if ((_control.ShowCommentsOnPreviewPage && (_control.CurrentAction == Blog.ActionType.Default || _control.CurrentAction == Blog.ActionType.AddComment)) || (_control.CurrentAction == Blog.ActionType.ViewPost && _control.ShowCommentsCountOnSinglePostView))
            {
                XmlNode node = doc.DocumentElement.SelectSingleNode("Comments");
                if (node != null)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                    writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);

                    CommentsManager.WriteComments(writer, node, _control);
                    writer.RenderEndTag();//td
                    writer.RenderEndTag();//tr
                }
            }
            if (_control.ShowPermalink)
            {
                RenderPermalink(curFileName);
            }
            writer.RenderEndTag();//table
        }

        private void RenderPermalink(string curFileName)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (!string.IsNullOrEmpty(_control.PermalinkCSS))
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.PermalinkCSS);
            }
            HtmlManager.SetFontStyles(_control.PermalinkFont, writer);
            writer.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(_control.PermalinkColor));
            string url;
            if (_control.IsDesignMode)
            {
                url = "{PageUrl}";
            }
            else
            {
                url = Path.GetFileName(HttpContext.Current.Request.PhysicalPath).TrimEnd('/') + "?postId=" + curFileName;
            }
            writer.AddAttribute(HtmlTextWriterAttribute.Href, url);

            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write(_control.PermalinkText);
            writer.RenderEndTag();
            
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr
        }

        private void RenderBody(bool fullBody, XmlDocument doc)
        {
            XmlNode node = doc.DocumentElement.SelectSingleNode("Body");
            if (node == null) throw new XmlException("Element \"Body\" was missing in the document");
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
            if (_control.PreviewPagePostBodyCSS != null)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.PreviewPagePostBodyCSS);
            }
            HtmlManager.SetFontStyles(_control.BodyFont, writer);
            writer.AddStyleAttribute(HtmlTextWriterStyle.Color,ColorTranslator.ToHtml( _control.BodyForeColor));
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (fullBody)
            {
                writer.Write(node.InnerText.Trim());
            }
            else
            {
                string body = node.InnerText.Trim();
                if (body.Length > _control.NumberOfCharsToDisplayForEachPostPreview)
                {
                    int space = body.IndexOf(" ", _control.NumberOfCharsToDisplayForEachPostPreview);
                    if (space == -1) space = _control.NumberOfCharsToDisplayForEachPostPreview;
                    body = body.Substring(0, space);
                }
                writer.Write(body);
            }
        }

        private void RenderSubjectLine(XmlDocument doc)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            RenderSubject(doc);
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            RenderCommentsCount(doc);
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            RenderPostWriter(doc);
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            RenderPublishDate(doc);
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr
        }

        private void RenderPostWriter(XmlDocument doc)
        {
            if (_control.ShowPostWriter)
            {
                XmlNode node = doc.DocumentElement.SelectSingleNode("Writer");
                if (node != null)
                {
                    if (_control.PostWriterCSS != null)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.PostWriterCSS);
                    }
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(_control.DateAuthorForeColor));
                    HtmlManager.SetFontStyles(_control.DateAuthorFont, writer);
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    if (_control.PostWriterFormat.Contains("{0}"))
                    {
                        writer.Write(_control.PostWriterFormat.Replace("{0}", node.InnerText.Trim()));
                    }
                    else
                    {
                        writer.Write(_control.PostWriterFormat);
                        writer.Write(node.InnerText.Trim());
                    }
                    writer.RenderEndTag();//span
                }
            }
        }

        private void RenderPublishDate(XmlDocument doc)
        {
            if (_control.ShowPostPublishDate)
            {
               XmlNode node = doc.DocumentElement.SelectSingleNode("Date");
                if (node != null)
                {
                    if (_control.PostPublishDateCSS != null)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.PostPublishDateCSS);
                    }
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(_control.DateAuthorForeColor));
                    HtmlManager.SetFontStyles(_control.DateAuthorFont, writer);
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    string date;
                    try
                    {
                        DateTime dt = DateTime.Parse(node.InnerText.Trim());
                        date = dt.ToString(_control.DateFormat);

                    }
                    catch
                    {
                        date = node.InnerText.Trim();
                    }
                    writer.Write(date);
                    writer.RenderEndTag();//span
                }
            }
        }

        private void RenderCommentsCount(XmlDocument doc)
        {
            if ((_control.CurrentAction == Blog.ActionType.Default && _control.ShowCommentsCountOnPreviewPage) ||
                _control.CurrentAction == Blog.ActionType.ViewPost && _control.ShowCommentsCountOnSinglePostView)
            {
                if (_control.CommentsCountCSS != null)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.CommentsCountCSS);
                }
                writer.AddStyleAttribute(HtmlTextWriterStyle.Color, ColorTranslator.ToHtml(_control.CommentsCountColor));
                HtmlManager.SetFontStyles(_control.CommentsFont, writer);
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(" ");
                writer.Write(CommentsManager.GetCommentsCount(doc));
                writer.Write(" ");
                writer.Write(_control.CommentLabelText);
                writer.RenderEndTag();
            }
        }

        private void RenderSubject(XmlDocument doc)
        {
            XmlNode node = doc.DocumentElement.SelectSingleNode("Title");
            FontInfo fi = _control.SubjectFont;
            HtmlManager.SetFontStyles(fi, writer);
            if (_control.PostSubjectCSS != null)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, _control.PostSubjectCSS);
            }
            if (_control.AllowSinglePostView)
            {
                LinkButton lb = (LinkButton)_control.Controls[_control.showFullPostIndex];
                lb.OnClientClick = "setCurrentId('" + curFileName + "');setCurrentAction('ViewPost');";
                lb.ForeColor = _control.SubjectForeColor;
                lb.Font.Underline = false;
                lb.Text = node.InnerText.Trim();
                lb.RenderControl(writer);
            }
            else
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                singlePostSubject = node.InnerText.Trim();
                writer.Write(node.InnerText.Trim());
                writer.RenderEndTag();//a or span
            }
        }
        private string singlePostSubject;
        /// <summary>
        /// for the single post page view
        /// </summary>
        internal void RenderSinglePostView()
        {
            writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            string[] files = FilesManager.LoadFilesNames(_control, _control.Directory);
            for (int i = 0; i < files.Length; i++)
            {
                if (Path.GetFileName(files[i]) == _control.CommandArgument + ".xml")
                {
                    
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            WritePost(files[i],true);
                        writer.RenderEndTag();//td
                    writer.RenderEndTag();//tr
                    _control.TriggerPostViewed(new PostViewedArguments(singlePostSubject, files[i]));

                    if (_control.ShowAddPostButton || _control.ShowBackButtonOnPostView)
                    {
                        writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        if (_control.ShowAddPostButton)
                        {
                            Button bt = (Button)_control.Controls[_control.addPostButtonIndex];
                            bt.RenderControl(writer);
                        }
                        writer.Write(" ");
                        if (_control.ShowBackButtonOnPostView)
                        {
                            Button back = (Button)_control.Controls[_control.newPostCancelIndex];
                            back.Text = _control.AddPostBackButtonText;
                            back.RenderControl(writer);
                        }
                        writer.RenderEndTag();//td
                        writer.RenderEndTag();//tr
                    }
                    writer.RenderEndTag();//table
                    return;
                }
            }
            writer.RenderEndTag();//shouldn't happen - table closing
        }
    }
}
